import axios, { InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import {
  ElNotification,
  ElMessageBox,
  ElMessage,
  ElLoading,
} from 'element-plus';
import { getToken } from '@/utils/auth';
import errorCode from '@/utils/errorCode';
import { tansParams, blobValidate } from '@/utils/ruoyi';
import cache from '@/plugins/cache';
import useUserStore from '@/store/modules/user';
import { saveAs } from 'file-saver';

let loadingInstance: ReturnType<typeof ElLoading.service> | null = null;
const LOADING_TIME: number = 1500;
export let isRelogin = { show: false };

// 创建 axios 实例
const service = axios.create({
  baseURL: '',
  timeout: 10000,
});

// 通用方法：处理重新登录
const handleRelogin = async () => {
  if (!isRelogin.show) {
    isRelogin.show = true;
    try {
      await ElMessageBox.confirm(
        '登录状态已过期，您可以继续留在该页面，或者重新登录',
        '系统提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning',
        }
      );
      isRelogin.show = false;
      await useUserStore().logOut();
      location.href = '/index';
    } catch (error) {
      console.log('error:', error);
      isRelogin.show = false;
    }
  }
  return Promise.reject('无效的会话，或者会话已过期，请重新登录。');
};

// 通用方法：显示消息
const showMessage = (
  msg: string,
  type: 'error' | 'warning' | 'success' = 'error'
) => {
  ElMessage({
    message: msg,
    type,
  });
};

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const isToken = (config.headers || {}).isToken === false;
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;

    const token = getToken();
    if (token && !isToken) {
      config.headers!['token'] = token;
    }

    if (config.method === 'get' && config.params) {
      let url = config.url + '?' + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }

    // 防止重复提交的逻辑
    if (
      !isRepeatSubmit &&
      (config.method === 'post' || config.method === 'put')
    ) {
      const requestObj = {
        url: config.url,
        data:
          typeof config.data === 'object'
            ? JSON.stringify(config.data)
            : config.data,
        time: new Date().getTime(),
      };

      const requestSize = Object.keys(JSON.stringify(requestObj)).length;
      const limitSize = 5 * 1024 * 1024; // 5MB 限制
      if (requestSize >= limitSize) {
        return config;
      }

      const sessionObj = cache.session.getJSON('sessionObj');
      const interval = 1000; // 时间间隔(ms)
      if (
        sessionObj &&
        sessionObj.url === requestObj.url &&
        sessionObj.data === requestObj.data &&
        requestObj.time - sessionObj.time < interval
      ) {
        return Promise.reject('重复提交');
      } else {
        cache.session.setJSON('sessionObj', requestObj);
      }
    }

    return config;
  },
  (error) => {
    setTimeout(() => {
      if (loadingInstance) loadingInstance.close();
    }, LOADING_TIME);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  async (res: AxiosResponse) => {
    setTimeout(() => {
      if (loadingInstance) loadingInstance.close();
    }, LOADING_TIME);

    const code = res.data.code || 200;
    const msg = errorCode[code] || res.data.msg || errorCode['default'];

    // 处理二进制数据
    if (
      res.request.responseType === 'blob' ||
      res.request.responseType === 'arraybuffer'
    ) {
      return res.data;
    }

    switch (code) {
      case 401:
      case 40310:
        return handleRelogin();
      case 40301:
        showMessage(msg, 'error');
        return res.data;
      case 500:
        showMessage(msg);
        return Promise.reject(new Error(msg));
      case 601:
        showMessage(msg, 'warning');
        return Promise.reject(new Error(msg));
      case 200:
      case 20000:
        return res.data;
      case 44444:
        showMessage(msg, 'error');
        return res.data;
      case 40000:
      case 50000:
        ElMessage({ message: msg, type: 'error' });
        return res;
      default:
        ElNotification.error({ title: msg });
        return Promise.reject(new Error(msg));
    }
  },
  (error) => {
    let { message } = error;
    if (message === 'Network Error') {
      message = '后端接口连接异常';
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时';
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常';
    }
    showMessage(message);
    return Promise.reject(error);
  }
);

// 通用下载方法
export async function download(
  url: string,
  params: any,
  filename: string,
  config?: any
): Promise<void> {
  loadingInstance = ElLoading.service({
    text: '正在下载数据，请稍候',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    const response = await service.post(url, params, {
      transformRequest: [(params) => tansParams(params)],
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
      ...config,
    });

    const isBlob = blobValidate(response.data);
    if (isBlob) {
      const blob = new Blob([response.data]);
      saveAs(blob, filename);
    } else {
      const resText = await response.data.text();
      const rspObj = JSON.parse(resText);
      const errMsg =
        errorCode[rspObj.code] || rspObj.msg || errorCode['default'];
      ElMessage.error(errMsg);
    }
  } catch (error) {
    console.error('下载文件出错：', error);
    ElMessage.error('下载文件出现错误，请联系管理员！');
  } finally {
    setTimeout(() => {
      if (loadingInstance) loadingInstance.close();
    }, LOADING_TIME);
    loadingInstance = null;
  }
}

export default service;
